package com.jqsoft.launcher.activity.setting;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.patientdb.PatientDao;
import com.jqsoft.launcher.util.DateTools;
import com.jqsoft.launcher.util.Log;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.ToastUtil;
import com.jqsoft.launcher.util.WebServiceUtils;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;

public class UpdateDBActivity extends JQActivity implements OnClickListener {
    private final String tag = "UpdateDBActivity";
    private String content;
    ProgressDialog dialog;
    private Button title_bar_right_button, updatemajor_btn;
    private TextView tv_gxy_des, tv_tnb_des, tv_zxjsb_des, tv_ertong_des,
            tv_yunchanfu_des;
    private int modelNum;
    private int updateNum;
    private SharedPreferences loginlist = null;

    private Thread downloadThread;
    private int currentPageIndex = 1;
    private int pageSize = 2000;

    private String getCurrentPageIndexString() {
        return String.valueOf(currentPageIndex);
    }

    private void resetCurrentPageIndex() {
        currentPageIndex = 1;
    }

    private void incrementCurrentPageIndex() {
        ++currentPageIndex;
    }

    private void decrementCurrentPageIndex() {
        --currentPageIndex;
        if (currentPageIndex < 1) {
            currentPageIndex = 1;
        }
    }

    private void stopDownload() {
        try {
            if (downloadThread != null) {
                downloadThread.interrupt();
                downloadThread = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopDownloadAndResetCurrentPageIndex() {
        stopDownload();
        resetCurrentPageIndex();
    }

    @Override
    protected int getContentLayout() {

        return R.layout.update_db;
    }

    @Override
    protected void initGui() {
        title_bar_right_button = (Button) findViewById(R.id.title_bar_right_button);
        updatemajor_btn = (Button) findViewById(R.id.updatemajor_btn);
        updatemajor_btn.setOnClickListener(UpdateDBActivity.this);
        tv_gxy_des = (TextView) findViewById(R.id.tv_gxy_des);
        tv_tnb_des = (TextView) findViewById(R.id.tv_tnb_des);
        tv_zxjsb_des = (TextView) findViewById(R.id.tv_zxjsb_des);
        tv_ertong_des = (TextView) findViewById(R.id.tv_ertong_des);
        tv_yunchanfu_des = (TextView) findViewById(R.id.tv_yunchanfu_des);

    }

    @Override
    protected void initAction() {
        setGoBack();
        title_bar_right_button.setVisibility(View.VISIBLE);
        title_bar_right_button.setText("全部下载");
        title_bar_right_button.setOnClickListener(UpdateDBActivity.this);

    }

    @Override
    protected void initData() {
        setTitle("下载数据库列表");
        loginlist = getSharedPreferences("LOGIN_INFOS", 0);
        String updateTime = loginlist.getString("updateTime", "");
        if (StringUtils.isNotBlank(updateTime)) {
            tv_gxy_des.setText(updateTime);
            tv_tnb_des.setText(updateTime);
            tv_zxjsb_des.setText(updateTime);
            tv_ertong_des.setText(updateTime);
            tv_yunchanfu_des.setText(updateTime);
        }
        dialog = new ProgressDialog(this);
        // 设置进度条风格，风格为圆形，旋转的
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // 设置ProgressDialog 标题图标
        dialog.setIcon(android.R.drawable.ic_dialog_alert);

        // 设置ProgressDialog 的一个Button
        // dialog.setButton("确定", new ProgressDialog.OnClickListener() {
        // @Override
        // public void onClick(DialogInterface dialog, int which) {
        //
        // }
        // });
        // 设置ProgressDialog 是否可以按退回按键取消
        dialog.setCancelable(true);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopDownloadAndResetCurrentPageIndex();
        if(dialog!=null && dialog.isShowing()){
            dialog.dismiss();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_bar_right_button:
                if (downloadThread != null && downloadThread.isAlive()) {
                    ToastUtil.showToast(this, "正在下载数据中");
                    return;
                }
                // loadWaitPanel();
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        stopDownloadAndResetCurrentPageIndex();
                    }
                });
                final PatientDao dao = new PatientDao(ctx);
                dao.deleteAll();
                downloadThread = new Thread() {
                    public void run() {
                        for (modelNum = 0; modelNum < 5; modelNum++) {

                            String requestUrl = "", methodName = "";
                            switch (modelNum) {
                                case 0:
                                    // 设置ProgressDialog 标题
                                    dialog.setTitle("高血压人员信息");
                                    // 设置ProgressDialog 提示信息
                                    dialog.setMessage("高血压下载进度条");
                                    requestUrl = BphsURL
                                            .getCommonPath("GetHypertensionManageData_URL");
                                    Log.i(tag, "查询:content" + requestUrl);
                                    methodName = BphsURL
                                            .getCommonPath("GetHypertensionManageData_METHOD");
                                    showMyHandle.sendEmptyMessage(Constant.SHOW_UPDATE);
                                    break;
                                case 1:
                                    requestUrl = BphsURL
                                            .getCommonPath("GetType2Diabetes_URL");
                                    methodName = BphsURL
                                            .getCommonPath("GetType2Diabetes_METHOD");
                                    break;
                                case 2:
                                    methodName = BphsURL
                                            .getCommonPath("GetPsychosisPersonManage_METHOD");
                                    requestUrl = BphsURL
                                            .getCommonPath("GetPsychosisPersonManage_URL");
                                    break;
                                case 3:
                                    methodName = BphsURL
                                            .getCommonPath("GetChildrenList_METHOD");
                                    requestUrl = BphsURL
                                            .getCommonPath("GetChildrenList_URL");
                                    break;
                                case 4:
                                    methodName = BphsURL
                                            .getCommonPath("GetPregnancyInfoManageData_METHOD");
                                    requestUrl = BphsURL
                                            .getCommonPath("GetPregnancyInfoManageData_URL");
                                    break;
                                default:
                                    break;
                            }

                            //
                            // String requestUrl =
                            // "http://60.171.146.122:9098/WebService/Andrews/PsychosisPersonWebService.asmx";
                            Log.i(tag, "查询:content" + requestUrl);
                            // String methodName="GetPsychosisPersonManageData";
//						JSONObject data = new JSONObject();
//						// {"sAreaCode":"340800","iCurrentPageIndex":"1","iPageSize":"10"}
//						try {
//							UserLoginInfo info = UserLoginInfo.getInstances();
//							data.put("sAreaCode",
//									info.getsManagementDivisionCode());//
//							data.put("iCurrentPageIndex", "1");
//							data.put("iPageSize", Integer.MAX_VALUE + ""); //
//						} catch (JSONException e1) {
//							// TODO Auto-generated catch block
//							e1.printStackTrace();
//						}
//						jiexidata(dao, requestUrl, methodName, data);
                            jiexidata(dao, requestUrl, methodName);
                        }
                    }

                    private void jiexidata(final PatientDao dao, String requestUrl,
                                           String methodName) {
                        resetCurrentPageIndex();
                        int downloadSizeSum = 0;
                        JSONObject data = new JSONObject();
                        // {"sAreaCode":"340800","iCurrentPageIndex":"1","iPageSize":"10"}
                        try {
                            UserLoginInfo info = UserLoginInfo.getInstances();
                            data.put("sAreaCode",
                                    info.getsManagementDivisionCode());//
                            data.put("iCurrentPageIndex", getCurrentPageIndexString());
                            data.put("iPageSize", pageSize + ""); //
                        } catch (JSONException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }

                        while (true) {
                            try {
                                content = WebServiceUtils.requestByParams(methodName,
                                        data.toString(), requestUrl);
                                if (StringUtils.isNotBlank(content)) {
                                    int downloadedSize = 0;
                                    Log.i(tag, "返回的查询结果" + content);
                                    // String result= content.replaceAll("\\\\", "");
                                    // Log.i(tag, "返回的查询结果"+result);
                                    JSONObject json = new JSONObject(content);
                                    // Log.i(tag, "返回的查询结果"+result);"AllCount":0,
                                    // allcount= 28;
                                    long allcount = json.getLong("AllCount");
                                    if (allcount != 0) {
                                        // 设置ProgressDialog的最大进度
//                                        dialog.setMax((int) allcount);
                                        setDialogMax((int) allcount);
                                        JSONObject jo = new JSONObject(
                                                json.getString("Data"));
                                        JSONArray jsonArray = (JSONArray) jo
                                                .get("Table");
                                        if (jsonArray != null) {
                                            downloadedSize = jsonArray.length();
                                            downloadSizeSum += downloadedSize;
                                        }
                                        for (int i = 0; jsonArray != null && i < jsonArray.length(); ++i) {
                                            JSONObject o = (JSONObject) jsonArray
                                                    .get(i);
                                            switch (modelNum) {
                                                case 0:
                                                    dao.add(o.getString("sPersonID"),
                                                            o.getString("sNo"),
                                                            o.getString("sPersonName"),
                                                            o.getString("sSexName"),
                                                            o.getString("dBirthday"),
                                                            o.getString("sCardNo"),
                                                            o.getString("sGradeName"),
                                                            o.getString("sDiagnosedHospital"),
                                                            o.getString("dDiagnosedTime"),
                                                            o.getString("sInputDeptName"),
                                                            o.getString("VisitingCount"),
                                                            o.getString("HealthyCheckUpCount"),
                                                            o.getString("iState"),o.getString("sphoto"),o.getString("sphoto1"));
                                                    break;
                                                case 1:
                                                    dao.addTNB(
                                                            o.getString("sPersonID"),
                                                            o.getString("sNo"),
                                                            o.getString("sPersonName"),
                                                            o.getString("sSexName"),
                                                            o.getString("dBirthday"),
                                                            o.getString("sCardNo"),
                                                            o.getString("sGradeName"),
                                                            o.getString("sDiagnosedHospital"),
                                                            o.getString("dDiagnosedTime"),
                                                            o.getString("sInputDeptName"),
                                                            o.getString("VisitingCount"),
                                                            o.getString("HealthyCheckUpCount"),
                                                            o.getString("iState"),o.getString("sphoto"),o.getString("sphoto1"));
                                                    break;
                                                case 2:
                                                    dao.addMajor(
                                                            o.getString("sPersonID"),
                                                            o.getString("sNo"),
                                                            o.getString("sPersonName"),
                                                            o.getString("sSexName"),
                                                            o.getString("dBirthday"),
                                                            o.getString("sCardNo"),
                                                            o.getString("sGuardianName"),
                                                            o.getString("sNowDiagnosis"),
                                                            o.getString("TreatmentEffect"),
                                                            o.getString("dFillTime"),
                                                            o.getString("sDoctorName"),
                                                            o.getString("sInputDeptName"),
                                                            o.getString("VisitingCount"),
                                                            o.getString("ExaminationCount"),
                                                            o.getString("iState"),o.getString("sphoto"));
                                                    break;
                                                case 3:
                                                    dao.addChild(o.getString("sPersonID"),
                                                            o.getString("sNo"),
                                                            o.getString("sPersonName"),
                                                            o.getString("sSexName"),
                                                            o.getString("dBirthday"),
                                                            o.getString("sCardNo"),
                                                            o.getString("sSexCode"),
                                                            o.getString("gKey"),
                                                            o.getString("sPhone"),
                                                            o.getString("sRegisterNo"),
                                                            o.getString("dRegisterDate"),o.getString("sphoto"));
                                                    break;
                                                case 4:
                                                    dao.addpregnantWomen(
                                                            o.getString("sPersonID"),
                                                            o.getString("sNo"),
                                                            o.getString("sPersonName"),
                                                            o.getString("sSexCode"),
                                                            o.getString("dBirthday"),
                                                            o.getString("sCardNo"),
                                                            o.getString("sPhone"),
                                                            o.getString("iPregnancytime"),
                                                            o.getString("gKey"),
                                                            o.getString("iState"),o.getString("sphoto"));
                                                    break;
                                                default:
                                                    break;
                                            }
                                        }
                                        //  dialog.setProgress(downloadSizeSum);
                                        setDialogProgress(downloadSizeSum);

                                    } else {
                                        updateNum = modelNum;
                                        showMyHandle.sendEmptyMessage(Constant.MSG_LOAD_OVER);
                                        break;
                                    }

//                                    updateNum = modelNum;
//                                    showMyHandle.sendEmptyMessage(Constant.MSG_LOAD_OVER);
//                                    Log.d("chenxu", "updateNum:"+updateNum+" begin next");
//                                    break;

                                    if (downloadedSize < pageSize) {
                                        updateNum = modelNum;
                                        showMyHandle.sendEmptyMessage(Constant.MSG_LOAD_OVER);
                                        break;
                                    } else {
                                        incrementCurrentPageIndex();
                                        data.put("iCurrentPageIndex", getCurrentPageIndexString());
                                    }

                                } else {
                                    showMyHandle.sendEmptyMessage(Constant.MSG_LOAD_ERROR);
                                }
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                showMyHandle
                                        .sendEmptyMessage(Constant.MSG_LOAD_ERROR);
                                e.printStackTrace();
                            }
                        }

                    }

                    private void setDialogMax(final int max){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dialog.setMax(max);
                            }
                        });
                    }

                    private void setDialogProgress(final int progress){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dialog.setProgress(progress);
                            }
                        });
                    }


//				private void jiexidata(final PatientDao dao, String requestUrl,
//                                       String methodName, JSONObject data) {
//					content = WebServiceUtils.requestByParams(methodName,
//							data.toString(), requestUrl);
//					if (StringUtils.isNotBlank(content)) {
//						try {
//							Log.i(tag, "返回的查询结果" + content);
//							// String result= content.replaceAll("\\\\", "");
//							// Log.i(tag, "返回的查询结果"+result);
//							JSONObject json = new JSONObject(content);
//							// Log.i(tag, "返回的查询结果"+result);"AllCount":0,
//							// allcount= 28;
//							long allcount = json.getLong("AllCount");
//							if (allcount != 0) {
//								// 设置ProgressDialog的最大进度
//								dialog.setMax((int) allcount);
//								JSONObject jo = new JSONObject(
//										json.getString("Data"));
//								JSONArray jsonArray = (JSONArray) jo
//										.get("Table");
//								for (int i = 0; i < jsonArray.length(); ++i) {
//									JSONObject o = (JSONObject) jsonArray
//											.get(i);
//									switch (modelNum) {
//									case 0:
//										dao.add(o.getString("sPersonID"),
//												o.getString("sNo"),
//												o.getString("sPersonName"),
//												o.getString("sSexName"),
//												o.getString("dBirthday"),
//												o.getString("sCardNo"),
//												o.getString("sGradeName"),
//												o.getString("sDiagnosedHospital"),
//												o.getString("dDiagnosedTime"),
//												o.getString("sInputDeptName"),
//												o.getString("VisitingCount"),
//												o.getString("HealthyCheckUpCount"),
//												o.getString("iState"));
//										break;
//									case 1:
//										dao.addTNB(
//												o.getString("sPersonID"),
//												o.getString("sNo"),
//												o.getString("sPersonName"),
//												o.getString("sSexName"),
//												o.getString("dBirthday"),
//												o.getString("sCardNo"),
//												o.getString("sGradeName"),
//												o.getString("sDiagnosedHospital"),
//												o.getString("dDiagnosedTime"),
//												o.getString("sInputDeptName"),
//												o.getString("VisitingCount"),
//												o.getString("HealthyCheckUpCount"),
//												o.getString("iState"));
//										break;
//									case 2:
//										dao.addMajor(
//												o.getString("sPersonID"),
//												o.getString("sNo"),
//												o.getString("sPersonName"),
//												o.getString("sSexName"),
//												o.getString("dBirthday"),
//												o.getString("sCardNo"),
//												o.getString("sGuardianName"),
//												o.getString("sNowDiagnosis"),
//												o.getString("TreatmentEffect"),
//												o.getString("dFillTime"),
//												o.getString("sDoctorName"),
//												o.getString("sInputDeptName"),
//												o.getString("VisitingCount"),
//												o.getString("ExaminationCount"),
//												o.getString("iState"));
//										break;
//									case 3:
//										dao.addChild(o.getString("sPersonID"),
//												o.getString("sNo"),
//												o.getString("sPersonName"),
//												o.getString("sSexName"),
//												o.getString("dBirthday"),
//												o.getString("sCardNo"),
//												o.getString("sSexCode"),
//												o.getString("gKey"),
//												o.getString("sPhone"),
//												o.getString("sRegisterNo"),
//												o.getString("dRegisterDate"));
//										break;
//									case 4:
//										dao.addpregnantWomen(
//												o.getString("sPersonID"),
//												o.getString("sNo"),
//												o.getString("sPersonName"),
//												o.getString("sSexCode"),
//												o.getString("dBirthday"),
//												o.getString("sCardNo"),
//												o.getString("sPhone"),
//												o.getString("iPregnancytime"),
//												o.getString("gKey"),
//												o.getString("iState"));
//										break;
//									default:
//										break;
//									}
//									dialog.setProgress(i + 2);
//								}
//							}
//						} catch (JSONException e) {
//							// TODO Auto-generated catch block
//							showMyHandle
//									.sendEmptyMessage(Constant.MSG_LOAD_ERROR);
//							e.printStackTrace();
//						}
//						// if(modelNum==3)
//						updateNum = modelNum;
//						showMyHandle.sendEmptyMessage(Constant.MSG_LOAD_OVER);
//					} else {
//						showMyHandle.sendEmptyMessage(Constant.MSG_LOAD_ERROR);
//					}
//				};
                };
                downloadThread.start();
                break;
            case R.id.updatemajor_btn:

                break;
            default:

                break;
        }

        return;
    }

    private final Handler showMyHandle = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constant.MSG_LOAD_OVER:
                    // dismissrogressBar();
                    String date = DateTools
                            .getFormatStringByDF_YYYY_MM_DD_HH_MM_SS(new Date());
                    switch (updateNum) {
                        case 0:
                            tv_gxy_des.setText("最新更新时间：" + date);
                            // 设置ProgressDialog 标题
                            dialog.setTitle("糖尿病人员信息");
                            // 设置ProgressDialog 提示信息
                            dialog.setMessage("糖尿病下载进度条");
                            break;
                        case 1:
                            tv_tnb_des.setText("最新更新时间：" + date);
                            // 设置ProgressDialog 标题
                            dialog.setTitle("重性精神病人员信息");
                            // 设置ProgressDialog 提示信息
                            dialog.setMessage("重性精神病下载进度条");
                            break;
                        case 2:
                            tv_zxjsb_des.setText("最新更新时间：" + date);
                            // 设置ProgressDialog 标题
                            dialog.setTitle("儿童保健信息");
                            // 设置ProgressDialog 提示信息
                            dialog.setMessage("儿童保健下载进度条");
                            break;
                        case 3:
                            tv_ertong_des.setText("最新更新时间：" + date);
                            // 设置ProgressDialog 标题
                            dialog.setTitle("孕产妇人员信息");
                            // 设置ProgressDialog 提示信息
                            dialog.setMessage("孕产妇下载进度条");
                            break;
                        case 4:
                            tv_yunchanfu_des.setText("最新更新时间：" + date);
                            loginlist.edit().putString("updateTime", "最新更新时间：" + date)
                                    .commit();
                            dialog.dismiss();
                            break;

                        default:
                            break;
                    }
                    // dialog.dismiss();
                    // MessageTools.showDialogOk(ctx, "更新成功!");
                    break;
                case Constant.MSG_LOAD_ERROR:
                    // dismissrogressBar();
                    stopDownloadAndResetCurrentPageIndex();
                    if (dialog!=null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    if (ctx!=null && (ctx instanceof Activity) && !((Activity)ctx).isFinishing()) {
                        MessageTools.showDialogOk(ctx, "更新失败!");
                    }
                    break;
                case Constant.SHOW_UPDATE:
                    // 显示
                    runOnUiThread(new Runnable() {
                        public void run() {
//                            System.out.println("1111");
                            if(!dialog.isShowing()){
                                dialog.show();
                            }
                        }
                    });
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };


}
